package io.renren.modules.ws.stomp;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import java.security.Principal;
import java.util.List;

/**
 * stomp用户认证
 * 提升优先级
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class AuthChannelInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

        //1、判断是否首次连接
        if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {
            // 2、拿到header Authorization
            List<String> nativeHeader = accessor.getNativeHeader("Authorization");
            if (nativeHeader != null && !nativeHeader.isEmpty()) {
                String token = nativeHeader.get(0);
                //3、可以结合其他认证token方式获取用户，此处直接拿Authorization为用户名
                if(token != null) {
                    Principal principal = new Principal() {
                        @Override
                        public String getName() {
                            return token;
                        }
                    };
                    accessor.setUser(principal);
                }
            }
        }
        return message;
    }
}
